package br.com.ava.core.infra.hibernate.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * UserType String para Enumera��es.
 * <p>
 * Tipo extendido do Hibernate para persistir constantes de Enumera��es do tipo
 * String. <br>
 * Toda Enumera��o que persistir deve implementar o m�todo
 * <code>public String getCodigo()</code>.
 * 
 * @param <E>
 *            Tipo de enumera��o que ser� persistido pela classe
 */
@SuppressWarnings("unchecked")
public class EnumStringUserType<E extends Enum<E>> implements UserType,
		ParameterizedType {

	/**
	 * Log
	 */
	private static final Logger LOG = LoggerFactory
			.getLogger(EnumStringUserType.class);

	/**
	 * SQL TYPES
	 */
	private static final int SQL_TYPE = Types.VARCHAR;
	private static final int[] SQL_TYPES = { SQL_TYPE };

	private Class<E> clazz;

	/**
	 * {@inheritDoc}
	 */
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object assemble(Serializable cache, Object owner)
			throws HibernateException {
		return cache;
	}

	/**
	 * {@inheritDoc}
	 */
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setParameterValues(Properties params) {
		String enumClassName = params.getProperty("enumClassName");
		if (enumClassName == null) {
			throw new MappingException("enumClass parameter not specified");
		}
		try {
			this.clazz = (Class<E>) Class.forName(enumClassName);
		} catch (java.lang.ClassNotFoundException e) {
			throw new MappingException("enumClass " + enumClassName
					+ " not found", e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isMutable() {
		return false;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		String codigo = rs.getString(names[0]);
		EnumeracaoComCodigoStringDescricao enumObject = null;
		if (rs.wasNull()) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Returning null as column '" + names[0] + "'.");
			}
		} else {
			enumObject = getEnum(codigo);
		}
		return enumObject;
	}

	/**
	 * M�todo que retorna o c�digo das constantes.
	 * 
	 * @param codigo
	 * @return
	 */
	private EnumeracaoComCodigoStringDescricao getEnum(String codigo) {
		Class<? extends Enum<E>> enumClass = returnedClass();
		Enum<E>[] enums = enumClass.getEnumConstants();
		for (int i = 0; i < enums.length; i++) {
			if (((EnumeracaoComCodigoStringDescricao) enums[i]).getCodigo()
					.equals(codigo)) {
				return (EnumeracaoComCodigoStringDescricao) enums[i];
			}
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public void nullSafeSet(PreparedStatement pstm, Object value, int index)
			throws HibernateException, SQLException {
		if (value == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Binding null to parameter: " + index);
			}
			pstm.setNull(index, SQL_TYPE);
		} else {
			String codigoEnum = ((EnumeracaoComCodigoStringDescricao) value)
					.getCodigo();
			if (LOG.isDebugEnabled()) {
				LOG.debug("Binding '" + codigoEnum + "' to parameter: " + index);
			}
			pstm.setString(index, codigoEnum);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Object replace(Object original, Object target, Object owner)
			throws HibernateException {
		return original;
	}

	/**
	 * {@inheritDoc}
	 */
	public Class<? extends Enum<E>> returnedClass() {
		return clazz;
	}

	/**
	 * {@inheritDoc}
	 */
	public int[] sqlTypes() {
		return SQL_TYPES.clone();
	}

	/**
	 * {@inheritDoc}
	 */
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y) { // NOPMD by deinf.dejalma - Implementa��o de
			// infra-estrutura. Nela � necess�rio avaliar se um
			// objeto � o mesmo (==) que outro.
			return true;
		}
		if (x == null || y == null) {
			return false;
		}
		return x.equals(y);
	}

}
